﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using Webdiyer.WebControls.Mvc;

namespace MinistryStandardPlatformWeb.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("16")]
        public ActionResult Index()
        {
            var users = from u in context.LoginUsers
                        orderby u.InsertTime descending
                        select u;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                users = from u in users
                          where u.CustomerID == id
                          orderby u.InsertTime descending
                          select u;

            }

            return PartialView(users.ToPagedList(1, CommonDictionary.PageSize));
        }

        [MenuAuthorized("164")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var users = from u in context.LoginUsers
                            orderby u.InsertTime descending
                            select u;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                users = from u in users
                            where u.CustomerID == unitId
                            orderby u.InsertTime descending
                            select u;

            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                users = from r in users
                        where ids.Contains(r.CustomerID)
                        orderby r.CustomerID, r.InsertTime descending
                        select r;
            }


            if (!string.IsNullOrEmpty(condition))
            {
                users = from u in users
                            where u.UserId.Contains(condition)
                            orderby u.InsertTime descending
                            select u;

            }
            return PartialView(users.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }

        [MenuAuthorized("161")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);
            return View(new LoginUsers()
                {
                    CustomerID=unitId,
                    CustomerName=unitName
                });
        }

        [HttpPost]
        [MenuAuthorized("161")]
        public ActionResult Create(LoginUsers user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (context.LoginUsers.Any(u => u.UserId == user.UserId))
                    {
                        ViewBag.Message = "添加失败,已经存在用户名为" +user.UserId+"的用户" ;
                    }
                    else
                    {
                        user.InsertTime = DateTime.Now;
                        user.Identity = "user";
                        user.InUserID = CommonFunctions.GetLoginUser().UserId;
                        context.LoginUsers.InsertOnSubmit(user);
                        context.SubmitChanges();
                        ViewBag.Message = "添加成功";
                    }
                   
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败,"+ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
            }

            return View(user);
        }

        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        [MenuAuthorized("162")]
        public ActionResult Delete(string parameters)
        {
            var user = context.LoginUsers.SingleOrDefault(u => u.UserId == parameters);
            try
            {
                context.LoginUsers.DeleteOnSubmit(user);
                context.SubmitChanges();
                return Json(new { success = true, message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [MenuAuthorized("163")]
        public ActionResult Edit(string id)
        {
            var user = context.LoginUsers.SingleOrDefault(u => u.UserId == id);
            return View(user);
        }

        [HttpPost]
        [MenuAuthorized("163")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var userToUpdate = context.LoginUsers.SingleOrDefault(u => u.UserId == form["UserId"]);
                string passowrd = userToUpdate.LoginPassword;
                UpdateModel(userToUpdate, form.ToValueProvider());
                //如果更改后的密码为空，说明没有更改密码，要将密码还原
                if (string.IsNullOrEmpty(userToUpdate.LoginPassword))
                {
                    userToUpdate.LoginPassword = passowrd;
                }
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                return View(userToUpdate);
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败,"+ex.Message;
                return View(new LoginUsers());
            }
        }
    }
}
